package com.fau.wmbj.server.controller;

import cn.hutool.core.util.StrUtil;
import com.fau.wmbj.server.config.CurrentUser;
import com.fau.wmbj.server.entity.Company;
import com.fau.wmbj.server.entity.Role;
import com.fau.wmbj.server.entity.Template;
import com.fau.wmbj.server.entity.User;
import com.fau.wmbj.server.flowable.domain.bo.ModelBo;
import com.fau.wmbj.server.flowable.entity.ActModel;
import com.fau.wmbj.server.flowable.pojo.ProcessModel;
import com.fau.wmbj.server.flowable.service.ActModelService;
import com.fau.wmbj.server.service.CompanyService;
import com.fau.wmbj.server.service.RoleService;
import com.fau.wmbj.server.service.TemplateService;
import com.fau.wmbj.server.service.UserService;
import com.fau.wmbj.server.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.converter.BpmnXMLConverter;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.repository.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 模板
 *
 * @author jiawei
 * @version 1.0
 * @datetime 2024-03-25 10:52
 */
@Slf4j
@RestController
@RequestMapping("/template")
public class TemplateController {

    @Resource
    private TemplateService templateService;
    @Resource
    private CompanyService companyService;
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private ActModelService actModelService;

    /**
     * 分页查询
     */
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    @ResponseBody
    public Message getPage(@RequestBody Pageable pageable, @CurrentUser User user) {
        Page<Template> page = templateService.findPage(pageable);
        List<Template> content = page.getContent();
        Company company = user.getRole().getCompany();
        if (company.getInUseTemplate() != null) {
            for (Template template : content) {
                if (Objects.equals(template.getId(), company.getInUseTemplate())) {
                    template.setIsDefault(true);
                }
            }
        }
        return Message.success(page);
    }

    /**
     * 根据id查询
     */
    @RequestMapping(value = "/get", method = RequestMethod.POST)
    @ResponseBody
    public Message getById(@RequestBody Template template) {
        Template template1 = templateService.find(template.getId());
        Map<String, Object> tableData = template1.getTableData();
        List<Map<String, Object>> baseParameter = (List<Map<String, Object>>) tableData.get("baseParameter");
        if (baseParameter == null) {
            baseParameter = new ArrayList<>();
        }
        List<Map<String, Object>> body = (List<Map<String, Object>>) tableData.get("body");
        if (body == null) {
            body = new ArrayList<>();
        }
        Integer headerRow = (Integer) tableData.get("headerRow");
        if (headerRow == null) {
            headerRow = 2;
        }
        List<Map<String, Object>> role = (List<Map<String, Object>>) tableData.get("role");
        template1.setBaseParameter(baseParameter);
        template1.setRole(role);
        template1.setBody(body);
        template1.setHeaderRow(headerRow);
        return Message.success(template1);
    }

    /**
     * 保存模板
     */
    @RequestMapping(value = "/saveBody", method = RequestMethod.POST)
    @ResponseBody
    public Message saveTableData(@RequestBody Template template) {
        Long id = template.getId();
        Template template1 = templateService.find(id);
        Map<String, Object> tableData = template1.getTableData();
        tableData.put("body", template.getBody());
        tableData.put("headerRow", template.getHeaderRow());

        template1.setTableData(tableData);
        templateService.update(template1);
        return Message.success(template1);
    }

    /**
     * 保存角色权限
     */
    @RequestMapping(value = "/saveRole", method = RequestMethod.POST)
    @ResponseBody
    public Message saveRole(@RequestBody Template template) {

        List<Map<String, Object>> roles = template.getRole();
        Long id = template.getId();
        Template template1 = templateService.find(id);
        Map<String, Object> tableData = template1.getTableData();
        tableData.put("role", roles);
        template1.setTableData(tableData);
        templateService.update(template1);
        return Message.success(template1);
    }

    /**
     * 保存基础参数
     */
    @RequestMapping(value = "/saveBaseParameter", method = RequestMethod.POST)
    @ResponseBody
    public Message saveBaseParameter(@RequestBody Template template) {
        Long id = template.getId();
        Template template1 = templateService.find(id);
        Map<String, Object> tableData = template1.getTableData();
        tableData.put("baseParameter", template.getBaseParameter());
        template1.setTableData(tableData);
        templateService.update(template1);
        return Message.success(template1);
    }

    /**
     * 保存表单参数
     */
    @RequestMapping(value = "/saveFormData", method = RequestMethod.POST)
    @ResponseBody
    public Message saveFormData(@RequestBody Template template) {
        Long id = template.getId();
        Template template1 = templateService.find(id);
        template1.setFormData(template.getFormData());
        templateService.update(template1);
        return Message.success(template1);
    }

    /**
     * 保存流程参数
     */
    @RequestMapping(value = "/saveFlowData", method = RequestMethod.POST)
    @ResponseBody
    public Message saveFlowData(@RequestBody Template template) {
        Long id = template.getId();
        Template template1 = templateService.find(id);
        Map<String, Object> flowData = template.getFlowData();
        ProcessModel processModel = template.getProcessModel();
        BpmnModel bpmnModel = processModel.toBpmnModel();
        byte[] xmlBytes = new BpmnXMLConverter().convertToXML(bpmnModel);
        String xml = "";
        if (Objects.nonNull(xmlBytes)) {
            xml = new String(xmlBytes, StandardCharsets.UTF_8);
            flowData.put("xml", xml);
            flowData.put("model_name", processModel.getName());
            flowData.put("model_code", processModel.getCode());
            String model_id = (String) flowData.get("model_id");
            ModelBo modelBo = new ModelBo();
            modelBo.setName(processModel.getName());
            modelBo.setKey(processModel.getCode());
            modelBo.setXml(StrUtil.utf8Str(xmlBytes));
            if (StringUtils.isNotEmpty(model_id)) {
                ActModel info = actModelService.getInfo(model_id);
                modelBo.setId(info.getId());
                Model update = actModelService.update(modelBo);
                flowData.put("model_id", update.getId());
            } else {
                Model model = actModelService.saveNewModel(modelBo);
                flowData.put("model_id", model.getId());
            }
        }
        template1.setFlowData(flowData);
        templateService.update(template1);
        return Message.success(template1);
    }

    /**
     * 添加
     */
    @RequestMapping("/save")
    public Message save(@RequestBody Template template, @CurrentUser User user) {
        template.setCompany(user.getRole().getCompany());
        Template save = templateService.save(template);
        if (template.getIsDefault()) {
            Company company = user.getRole().getCompany();
            company.setInUseTemplate(save.getId());
            companyService.update(company);
        }
        return Message.success();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public Message update(@RequestBody Template template, @CurrentUser User user) {
        template.setCompany(user.getRole().getCompany());
        if (template.getIsDefault()) {
            Company company = user.getRole().getCompany();
            company.setInUseTemplate(template.getId());
            companyService.update(company);
        }
        templateService.update(template);
        return Message.success();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public Message delete(@RequestBody Template template) {
        List<Long> ids = template.getIds();
        try {
            templateService.delete(ids);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Message.error(e.getMessage());
        }
        return Message.success();
    }

    /**
     * 获取用户
     */
    @RequestMapping(value = "/user-list", method = RequestMethod.POST)
    @ResponseBody
    public Message getUserList(@RequestBody Pageable pageable, @CurrentUser User user) {
        List<Filter> filters = pageable.getFilters();
        filters.add(Filter.eq("role.company", user.getRole().getCompany()));
        Page<User> page = userService.findPage(pageable);
        return Message.success(page);
    }

    /**
     * 获取用户
     */
    @RequestMapping(value = "/getUser", method = RequestMethod.POST)
    @ResponseBody
    public Message getUser(@RequestBody User user, @CurrentUser User currentUser) {
        List<Filter> filters = new ArrayList<>();
        filters.add(Filter.eq("role.company", currentUser.getRole().getCompany()));
        filters.add(Filter.eq("email", user.getUsername()));
        List<User> list = userService.findList(1, filters, null);
        return Message.success(list == null || list.isEmpty() ? null : list.get(0));
    }

    /**
     * 获取角色
     */
    @RequestMapping(value = "/role-list", method = RequestMethod.POST)
    @ResponseBody
    public Message getRoleList(@RequestBody Pageable pageable, @CurrentUser User user) {
        List<Filter> filters = pageable.getFilters();
        filters.add(Filter.eq("company", user.getRole().getCompany()));
        Page<Role> page = roleService.findPage(pageable);
        return Message.success(page);
    }

    /**
     * 获取角色
     */
    @RequestMapping(value = "/getRole", method = RequestMethod.POST)
    @ResponseBody
    public Message getRole(@RequestBody Role role, @CurrentUser User currentUser) {
        List<Filter> filters = new ArrayList<>();
        filters.add(Filter.eq("company", currentUser.getRole().getCompany()));
        filters.add(Filter.eq("code", role.getCode()));
        List<Role> list = roleService.findList(1, filters, null);
        return Message.success(list == null || list.isEmpty() ? null : list.get(0));
    }


    /**
     * 部署模型
     */
    @RequestMapping(value = "/modelDeploy", method = RequestMethod.POST)
    @ResponseBody
    public Message modelDeploy(@RequestBody Template template, @CurrentUser User currentUser) throws InterruptedException {
        Long id = template.getId();
        Template template1 = templateService.find(id);
        Map<String, Object> flowData = template1.getFlowData();
        String model_id = (String) flowData.get("model_id");
        if (StringUtils.isNotEmpty(model_id)) {
            actModelService.modelDeploy(model_id);
        }
        return Message.success();
    }



}
